package com.dingup.provider.util;

import com.dingup.util.GCookieUtil;
import org.apache.commons.lang.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import static com.dingup.provider.util.ConstUtil.COOKIE_ITEM_WX_USER_INFO;

/**
 * Created by jun on 2018/8/8.
 */
public class CookieUtil {
    public static void addCookie(HttpServletResponse response, String name, String value, int maxAge) {
        try {
            value = URLEncoder.encode(value, "UTF-8");
        } catch (UnsupportedEncodingException var5) {
            var5.printStackTrace();
        }

        Cookie cookie = new Cookie(name, value);
        cookie.setPath("/");
        cookie.setDomain("topschool.com");
        if (maxAge > 0) {
            cookie.setMaxAge(maxAge);
        }
        response.addCookie(cookie);
    }

    public static void delCookie(HttpServletResponse response, String name) {
        Cookie cookie = new Cookie(name, StringUtils.EMPTY);
        cookie.setPath("/");
        cookie.setDomain("topschool.com");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
    }

    public static String getOpenid(HttpServletRequest request) throws Exception {
        Cookie cookie = GCookieUtil.getCookieByName(request, COOKIE_ITEM_WX_USER_INFO);
        if (cookie == null) {
            throw new Exception("获取微信数据失败!");
        }
        return cookie.getValue();
    }
}
